﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.IO;

namespace PoshBoardWCF
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
    {
        public string ExecutePowerShellCode(string strPoshCode)
        {
            // Read Buil-in scripts
            //StreamReader objReader = new StreamReader("/scripts/PoshBoard.ps1", System.Text.Encoding.UTF8);
            //string strBuiltInScript = objReader.ReadToEnd();
            //objReader.Close();
            string strCodeToLaunch = strPoshCode;

            // create Powershell runspace            
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(strCodeToLaunch);
            pipeline.Commands.Add("out-string");

            Collection<PSObject> results = null;
            try
            {
                results = pipeline.Invoke();
            }
            catch (RuntimeException e)
            {
                // Display a message and exit if a RuntimeException is thrown
                string strError = e.GetType().Name + ": " + e.Message;
                return strError;
            }
            runspace.Close();

            foreach (PSObject thisResult in results)
            {

            }
            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            string strDataInput = stringBuilder.ToString();
            return strDataInput;
        }
        // Add more operations here and mark them with [OperationContract]
    }

}